const app = getApp()
const { page } = require('../../../api/order');
const {upTime} = require('/util/public')
Page({
    data: {
      config: app.config,
      
      items: [
          { name: '计划有变', value: '计划有变', checked: true },
          { name: '预收租金/补押金', value: '预收租金/补押金' },
          { name: '运费问题', value: '运费问题' },
          { name: '审核时间过长', value: '审核时间过长' },
          { name: '商家没货/服务态度问题', value: '商家没货/服务态度问题' },
        ],
        popShow: false,
        causeCon: '计划有变',
        cancelId: '',
        cancelStatus: '',
        pageData:{},
        systemSta: 1
    },
    onLoad(query) {
        this.getSystem();
        this.setData({
          pageData : query
        })
        app._init_(this)
        this.setData({ query })
        this.get_msg()
    },

    // 获取信息
    get_msg() {
        app.order.detail(this.data.query.param)
        .then(res=>{
            
            res.data.params = JSON.parse(res.data.params);
            res.data.paymentParams = JSON.parse(res.data.paymentParams);

            res.data.params.saleQuantity = res.data.params.numberDevices ? res.data.params.numberDevices : 1;

            // 期数
            res.data.leaseTerm = parseInt(res.data.leaseTerm);
            // 首期租金
            console.log("price->{}", res.data.params.model.price/100)
            let yu = res.data.params.model.price % res.data.leaseTerm;
            
            // res.data.firstRent = (res.data.params.model.price / res.data.leaseTerm / 100).toFixed(2)
            res.data.firstRent = ((((res.data.params.model.price / res.data.leaseTerm - yu) / 100).toFixed(2))*res.data.params.saleQuantity).toFixed(2);

			// if (res.data.leaseTerm == 30 || res.data.leaseTerm  == 14 || res.data.leaseTerm  == 24) {
			// 	res.data.firstRent = ((res.data.params.smash) / 100).toFixed(2);
			// }


            // 活动显示价格——首月一元
            let activePrice = (res.data.params.model.price - 100) / (res.data.leaseTerm-1);
            // 活动剩余租金——首月一元
            res.data.activeLastRent = (((activePrice / 100).toFixed(2))*res.data.params.saleQuantity).toFixed(2);


       
            // 总租金
            res.data.allRent = ((res.data.params.model.price / 100)*res.data.params.saleQuantity).toFixed(2);//app.fenToYuan(res.data.params.allRent);
            // 总押金
            res.data.allDeposit = ((res.data.params.deposit / 100)*res.data.params.saleQuantity).toFixed(2);//app.fenToYuan(res.data.params.allDeposit);
            // 完结价
            res.data.buyoutPrice = ((res.data.params.buyOutPrice / 100)*res.data.params.saleQuantity).toFixed(2)
            // 完结价
            res.data.buyoutPrice = res.data.buyoutPrice - res.data.allRent
            console.log('总租金',res.data.allRent )

            console.log('到期买断价', )
            

            // 套餐状态
            res.data.staShow = res.data.params.detail.substring(0,4);

            res.data.date = upTime("%Y-%M-%D %h:%m:%s", res.data.createtime);
            res.data.createtime = upTime("%Y-%M-%D", res.data.createtime);
            res.data.starttime = upTime("%Y-%M-%D", res.data.starttime)||'';
            res.data.endtime = upTime("%Y-%M-%D", res.data.endtime)||'';
            
            

            console.log(11111111,res.data)

            let puyAmount = 0
            res.data.productOrderRecordVoList.forEach(item => {
                 item.createtime = item.createtime?upTime("%Y-%M-%D", item.createtime):'';
                item.expiretime = item.expiretime?upTime("%Y-%M-%D", item.expiretime):'';
                item.duetime = item.duetime?upTime("%Y-%M-%D", item.duetime):'';
                if (item.payment == 1) {
                    puyAmount += item.price / 100
                }
            })
            res.data.puyAmount = puyAmount
            let item = res.data
            console.log(item)
            // this.setData(res.data);
            this.setData({ item: item });

            console.log(222222,this.data)
        })
    },
    //   联系商家
    makePhoneCall(e) {
        // console.log(e.target.dataset.phone)
        let phone = e.target.dataset.phone;
        my.makePhoneCall({ number: phone });
    },


    // 取消原因选择
    radioChange(e){
      let con = e.detail.value;
      this.setData({
        causeCon: con
      })
    },

    // 关闭取消弹窗
    popCancelBtn(){
      this.setData({
        cancelId: '',
        cancelStatus: '',
        causeCon: '计划有变',
        popShow: false
      })
    },

    // 确认取消
    popAffirmBtn(){
      console.log(this.data.causeCon,this.data.cancelId,this.data.cancelStatus,'原因');

      if (this.data.cancelStatus == 1) {
          app.order.canOrder(this.data.cancelId,{cont: this.data.causeCon})
          .then((res)=>{
              my.alert({
                  title: "取消成功",
                  success: () => {
                      this.popCancelBtn();
                      this.onLoad(this.data.pageData);
                  }
              });
          })
      } else if (this.data.cancelStatus == 2) {
          app.order.requestCanOrder(this.data.cancelId,{cont: this.data.causeCon})
          .then((res)=>{
              console.log(res)
              my.alert({
                  title: "申请成功",
                  success: () => {
                      this.popCancelBtn();
                      this.resetOrder();
                  }
              });
              
          })
      }
    },



    // 关闭订单, 申请取消
    onCancel(e) {
        // console.log(e.target.dataset.item)
        let id = e.target.dataset.item.id;
        let status = e.target.dataset.item.status;
        console.log(e,'滴滴');

        this.setData({
          cancelId: id,
          cancelStatus: status,
          popShow: true
        })

        // my.prompt({
        //     title: '申请取消',
        //     message: '请输入取消原因，否则无法为你取消',
        //     placeholder: '请输入取消原因',
        //     okButtonText: '确定',
        //     cancelButtonText: '取消',
        //     success: (result) => {
        //         console.log(result)
        //         if (!result.ok) {
        //             return
        //         }
        //         if (result.inputValue) {
        //             if (status == 1) {
        //                 app.order.canOrder(id,{cont: result.inputValue})
        //                 .then((res)=>{
        //                     my.alert({
        //                         title: "取消成功",
        //                         success: () => {
        //                             this.resetOrder()
        //                         }
        //                     });
        //                 })
        //             } else if (status == 2) {
        //                 app.order.canOrder(id,{cont: result.inputValue})
        //                 .then((res)=>{
        //                     console.log(res)
        //                     my.alert({
        //                         title: "申请成功",
        //                         success: () => {
        //                             this.resetOrder()
        //                         }
        //                     });
                            
        //                 })
        //             }
        //         } else {
        //             my.showToast({
        //                 type: 'exception',
        //                 content: '请输入取消原因',
        //             });
        //         }
        //     },
        // });
    },
    // 撤销申请
    noCancel(e){
        let cancelRequests = e.target.dataset.item.productOrderCancelRequests
        let id = cancelRequests[cancelRequests.length-1].id
        my.confirm({
            title: '温馨提示',
            content: '是否撤回订单取消申请',
            confirmButtonText: '立即撤回',
            cancelButtonText: '暂不撤回',
            success: (result) => {
                if (result.confirm) {
                    app.order.repeal(id)
                    .then(red=>{
                        if(res.code==200) {
                            my.alert({
                                title: "撤回成功",
                                success: () => {
                                    this.resetOrder()
                                }

                            });
                        }
                    })
                }
            },
        });
    },

     // 冻结
    onBuy(e) {
        let that = this
        const data = e.target.dataset.data;
        app.order.freeze(data.id)
        .then(pay=>{
            my.tradePay({
                orderStr: pay.data, // 完整的支付参数拼接成的字符串，从服务端获取
                success: (res) => {
                    console.log(res)
                    if (res.resultCode == 9000) {
                        my.alert({
                            content: "支付成功",
                        });
                        this.resetOrder()
                    } 
                },
                fail: (res) => {
                    my.alert({
                        content: res.memo,
                    });
                }
            });
        })
    },
    // 支付
    onReplenish(e) {
        let that = this
        let oid = e.target.dataset.data.productOrderRecordVoList[0].oid
        let id = e.target.dataset.data.productOrderRecordVoList[0].id
        app.order.alipay(oid,id)
        .then(res=>{
            my.tradePay({
                tradeNO: res.data,
                success: function (res) {
                    // console.log(res)
                    if (res.resultCode == 9000) {
                        my.alert({
                            content: "支付成功",
                        });
                        this.resetOrder()
                    } else {
                        my.alert({
                            content: res.memo,
                        });
                    }
                },
                
            });
        })
    },
     // 确认收货
    ConfirmReceipt(e) {
        let id = e.target.dataset.id
        app.order.receiving(id)
        .then(res=>{
            if (res.code == 200) {
                my.alert({
                    content: "提交成功",
                    success: () => {
                        this.resetOrder()
                    }
                })
            } else {
                my.alert({
                    content: res.msg
                })
            }
        })
    },

    // 跳转
    navigateTo(e){
        app.navigateTo(e);
    },

    // alipays编码
    getSignUrl(aliSchema) {
        if(!aliSchema){return  ''}
        const querys = aliSchema.split('?')[1].split('&');
        const signUrlKeyValue = querys.find((item) => item.includes('query=')).replace('query=', '');
        const encodedSignUrl = decodeURIComponent(signUrlKeyValue).replace('signUrl=', '');
        return encodedSignUrl
    },

    //代扣合同跳转长
    goExteriorPage(e){

      my.requestSubscribeMessage({
        entityIds: ['1409d0ab343147a8bc17cdb1f6b2843d', '4ee18d5b94fa488591a948a617715734'],
        complete: (res) => {

          let mylContractSignUrl = e.target.dataset.data;
          let signUrl = this.getSignUrl(mylContractSignUrl);

          my.navigateToMiniProgram({
              appId: '2021001152620480',
              path:`pages/signH5/index?signUrl=${signUrl}`,
              success: (res) => {
                console.log(JSON.stringify(res))
                // my.alert({
                //   title: JSON.stringify(res)
                // });
              },
              fail: (res) => {
                console.log(JSON.stringify(res));
                my.alert({
                  title: JSON.stringify(res),
                });
              }
          });

        }
      });
      
      

    },


    getSystem(){
      let systemInfo = my.getSystemInfoSync();
      let sta = 1;
      if(systemInfo.platform === "android"){
        sta = 1;
      }else{
        sta = 2;
      }
      this.setData({
        systemSta: sta,
      })
    },

});